// 实现这个项目的构建任务
const { src, dest, parallel, series, watch } = require('gulp')

const del = require('del')
const browserSync = require('browser-sync')

const loadPlugins = require('gulp-load-plugins');
const eslint = require('gulp-eslint')
const scsslint = require('gulp-scss-lint')
const minimist = require('minimist');
const plugins = loadPlugins()
const bs = browserSync.create() //创建开发服务器

const data = {
    menus: [
        {
            name: 'Home',
            icon: 'aperture',
            link: 'index.html'
        },
        {
            name: 'Features',
            link: 'features.html'
        },
        {
            name: 'About',
            link: 'about.html'
        },
        {
            name: 'Contact',
            link: '#',
            children: [
                {
                    name: 'Twitter',
                    link: 'https://twitter.com/w_zce'
                },
                {
                    name: 'About',
                    link: 'https://weibo.com/zceme'
                },
                {
                    name: 'divider'
                },
                {
                    name: 'About',
                    link: 'https://github.com/zce'
                }
            ]
        }
    ],
    pkg: require('./package.json'),
    date: new Date()
}

const clean = () => {
    return del(['dist', 'temp'])
}

const style = () => {
    return src('src/assets/styles/*.scss', { base: 'src' })
        .pipe(plugins.sass( //sass会默认不转换以_开头的文件
            { outputStyle: 'expanded' } //expanded为完全展开，即把转换后的文本按照正常使用的习惯展开
        ))
        .pipe(dest('temp'))
        .pipe(bs.reload({ stream: true }))
}

const script = () => {
    return src('src/assets/scripts/*.js', { base: 'src' })
        .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
        .pipe(dest('temp'))
        .pipe(bs.reload({ stream: true }))
}
const lintscript = () => {
    return src('src/assets/scripts/*.js', { base: 'src' })
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
}
const lintstyle = () => {
    return src('/scss/*.scss')
        .pipe(scsslint());
}
const lint = parallel(lintscript, lintstyle) //检测代码规范
const page = () => {
    return src('src/*.html', { base: 'src' })
        .pipe(plugins.swig({ data, defaults: { cache: false } })) // 防止模板缓存导致页面不能及时更新
        .pipe(dest('temp'))
        .pipe(bs.reload({ stream: true }))
}

const image = () => {
    return src('src/assets/images/**', { base: 'src' })
        .pipe(plugins.imagemin())
        .pipe(dest('dist'))
}

const font = () => {
    return src('src/assets/fonts/**', { base: 'src' })
        .pipe(plugins.imagemin())
        .pipe(dest('dist'))
}

const extra = () => {
    return src('public/**', { base: 'public' })
        .pipe(dest('dist'))
}

const serve = () => {
    watch('src/assets/styles/*.scss', style)
    watch('src/assets/scripts/*.js', script)
    watch('src/*.html', page)
    watch([
        'src/assets/images/**',
        'src/assets/fonts/**',
        'public/**'
    ], bs.reload)

    bs.init({
        notify: false,
        port: 2080,
        // open: false,
        // files: 'dist/**',
        server: {
            baseDir: ['temp', 'src', 'public'],
            routes: {
                '/node_modules': 'node_modules'
            }
        }
    })
}
const servepro = () => {
    bs.init({
        notify: false,
        port: 2080,
        open: false,
        files: 'dist/**',
        server: {
            baseDir: 'dist'
        }
    })
};
let knownOptions = {
    string: 'env',
    default: { env: process.production || 'false' }
};
let options = minimist(process.argv.slice(2), knownOptions);
const upload = () => {
    console.log('uploading')
    return src('dist/**')
        .pipe(sftp({
            host: '8.8.8.8',
            user: 'Administrator',
            port: '9999',
            pass: '123123132',
            remotePath: '/'
        }))
}
const deploy = done => {
    console.log(options)
    if(options.production==true){
        console.log('true')
        series(build, upload)
    }else{
        console.log('false');
        console.log(options)
        develop
    }
    //options.production == true ?  : develop
    done()
}
const useref = () => {
    return src('temp/*.html', { base: 'temp' })
        .pipe(plugins.useref({ searchPath: ['temp', '.'] }))
        // html js css
        .pipe(plugins.if(/\.js$/, plugins.uglify()))
        .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
        .pipe(plugins.if(/\.html$/, plugins.htmlmin({
            collapseWhitespace: true,
            minifyCSS: true,
            minifyJS: true
        })))
        .pipe(dest('dist'))
};
//构建优化
//parallel:相当于异步
//series:相当于同步
const compile = parallel(style, script, page); //同时进行
// 上线之前执行的任务
const build = series( //顺序进行
    clean,
    parallel( //同时进行
        series(compile, useref),
        image,
        font,
        extra
    )
)
const develop = series(compile, serve)
const start = series(build, servepro)
module.exports = {
    clean,
    lint,
    serve,
    build,
    develop,
    start,
    deploy
}